﻿namespace Repositories;
/// <summary>
/// sqlsugar配置
/// </summary>
public static class SqlsugarSetup
{
    /// <summary>
    /// 注册sqlsugar
    /// </summary>
    public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration, DbType dbType = SqlSugar.DbType.MySql, string dbName = "DefaultConnection")
    {
        SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
        {
            DbType = dbType,
            ConnectionString = configuration.GetConnectionString(dbName),
            IsAutoCloseConnection = true,
            //DatabaseModel：非mysql模式启用mysql模式的兼容
            //DisableNvarchar=true ,将参数全部转成varchar模式
            MoreSettings = new ConnMoreSettings() { DatabaseModel = DbType.MySql, DisableNvarchar = true }
        },
        db =>
        {
            //单例参数配置，所有上下文生效
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                //Console.WriteLine(sql);//输出sql
            };
            db.Aop.OnExecutingChangeSql = (sql, pars) => //可以修改SQL和参数的值
            {
                if (pars != null)
                {
                    foreach (var item in pars)
                    {
                        var startIndex = sql.IndexOf(item.ParameterName) - 3;
                        if (startIndex > 0 && sql.Substring(startIndex, 1) == "%")
                        {
                            if (item.Value != null && item.Value.ToString() != null && (item.Value.ToString().Contains("%") || item.Value.ToString().Contains("_")))
                            {
                                //重点看这儿，把参数名变成正常的名字
                                item.Value = item.Value.ToString()
                                            .Replace("%", "\\%")
                                            .Replace("_", "\\_");

                            };
                        }
                    }
                }
                return new KeyValuePair<string, SugarParameter[]>(sql, pars);
            };
        });
        services.AddSingleton<ISqlSugarClient>(sqlSugar);
    }
}
